import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { verifyToken } from '@/lib/auth';
import { cookies } from 'next/headers';

export async function GET(request: NextRequest) {
  const token = cookies().get('token')?.value;
  if (!token) {
    console.log('GET /api/profile: Missing token');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  let payload;
  try {
    payload =await verifyToken(token);
  } catch (error) {
    console.error('GET /api/profile: Invalid token', error);
    return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
  }

  if (!payload) {
    console.log('GET /api/profile: Invalid payload');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
//   console.log('GET /api/profile: Payload', payload);
  try {
    const user = await prisma.user.findUnique({
      where: { id: payload.user_id },
      select: {
        id: true,
        email: true,
        name: true,
        position: true,
        role: true,
        status: true,
        created_at: true
      }
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    return NextResponse.json(user);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch profile' }, { status: 500 });
  }
}

export async function PUT(request: NextRequest) {
  const token = cookies().get('token')?.value;
  if (!token) {
    console.log('PUT /api/profile: Missing token');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  let payload;
  try {
    payload = await verifyToken(token);
  } catch (error) {
    console.error('PUT /api/profile: Invalid token', error);
    return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
  }

  if (!payload) {
    console.log('PUT /api/profile: Invalid payload');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { name, position } = await request.json();

    // 验证请求数据
    if (!name || !position) {
      return NextResponse.json({ error: 'Name and position are required' }, { status: 400 });
    }

    const updatedUser = await prisma.user.update({
      where: { id: payload.user_id },
      data: {
        name,
        position
      },
      select: {
        id: true,
        email: true,
        name: true,
        position: true,
        role: true,
        status: true,
        created_at: true
      }
    });

    return NextResponse.json(updatedUser);
  } catch (error) {
    console.error('PUT /api/profile: Failed to update profile', error);
    return NextResponse.json({ error: 'Failed to update profile' }, { status: 500 });
  }
}

